package str.list;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: Timo
 * @Date: 2019/5/31 09:53
 * @Description: 计算List集合中的某个值的和
 * 使用的是JDk8的新特性 stream()
 */
public class ListSum {

    public static void main(String[] args) {
        test_1();
        test_2();
    }

    public static void test_1() {
        Integer[] integerArray = {1, 3, 5, 10, 18};

        List<Integer> list = new ArrayList<>(Arrays.asList(integerArray));

        IntSummaryStatistics summaryStatistics = list.stream().mapToInt((s) -> s).summaryStatistics();
        System.out.println("总和：" + summaryStatistics.getSum());
        System.out.println("平均数：" + summaryStatistics.getAverage());
        System.out.println("总个数：" + summaryStatistics.getCount());
        System.out.println("最大值：" + summaryStatistics.getMax());
        System.out.println("最小值：" + summaryStatistics.getMin());
    }

    public static void test_2() {
        List<User> userList = new ArrayList<>();
        userList.add(new User(1,10));
        userList.add(new User(2,20));
        userList.add(new User(3,30));

        int ageSum = userList.stream().collect(Collectors.summingInt(User::getAge));
        System.out.println("年龄总和" + ageSum);
    }
}


@Data
@NoArgsConstructor
@AllArgsConstructor
class User {
    private int id;
    private int age;
}
